package com.algorithm.lesson_04;

import java.util.Stack;

public class GetMinStackImpl2 implements GetMinStack<Integer> {

	private Stack<Integer> dataStack;
	private Stack<Integer> minStack;

	public GetMinStackImpl2() {
		dataStack = new Stack<>();
		minStack = new Stack<>();
	}

	@Override
	public boolean isEmpty() {
		return dataStack.isEmpty();
	}

	@Override
	public Integer peek() {
		if (dataStack.isEmpty()) {
			throw new RuntimeException("Your Stack is Empty!");
		}
		return dataStack.peek();
	}

	@Override
	public Integer pop() {
		if (dataStack.isEmpty()) {
			throw new RuntimeException("Your Stack is Empty!");
		}
		// 出栈操作
		Integer topData = dataStack.peek();
		Integer topMin = minStack.peek();
		if (topData <= topMin) {
			minStack.pop();
		}
		return dataStack.pop();
	}

	@Override
	public void push(Integer t) {
		// 压栈操作
		if (dataStack.isEmpty()) {
			dataStack.push(t);
			minStack.push(t);
			return;
		}
		Integer top = minStack.peek();
		// t<=top push-->t else no push
		if (t <= top) {
			minStack.push(t);
		}

		dataStack.push(t);
	}

	@Override
	public Integer getMin() {
		if (dataStack.isEmpty()) {
			throw new RuntimeException("Your Stack is Empty!");
		}
		return minStack.peek();
	}

}
